#include <stdio.h>

//顺序查找
int seq_search(int array[], int n, int k, int seek_seq[]){
    for (int i = 0; i < n; ++i) {
        if(array[i] == k){
            seek_seq[i] = i;
            return 0;
        } else{
            seek_seq[i] = i;
        }
    }
    return -1;
}

//顺序查找
int bin_search(int array[],int n,int k, int seek_seq[]){
    int low=0, high=n-1, mid;
    int i = 0;  //用来记录seek_seq[]元组的下标，使得查找记录能依次存入该数组中；
    while (low <= high){
        mid = (low + high)/2;
        seek_seq[i] = mid;
        if(k == array[mid]){
            return 0;   //查找成功返回0;
        }
        else if(k < seek_seq[mid]){
            high = mid-1;
        }
        else{
            low = mid+1;
        }
        i++;
    }
    return -1;  //表中不存在待查元素;
}

void main(){
    int array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int n = 10;
    int k = 8;
    int seek_seq[10];
    for (int j = 0; j < n; ++j) {
        seek_seq[j] = -1;
    }

    printf("给定的顺序表是:");
    for (int m = 0; m < n; ++m) {
        printf(" %d", array[m]);
    }
    printf("\n");
    printf("待查找元素K是: %d\n\n", k);

    printf("顺序查找-----\n");
    seq_search(array, n, k, seek_seq);

    printf("查找顺序:");
    for (int i = 0; i < n; ++i) {   //此处for循环用来显示查找顺序记录。当然也可以判断是否查找到了。如果i小于10就跳出循环，说明查找到了
        if(seek_seq[i] < 0){        //然而有一个bug就是可能最后一个刚好符合。
            break;
        }
        printf(" %d", array[seek_seq[i]]);
    }
    printf("\n\n");

    //将seek_seq数组重新初始化;
    for (int j = 0; j < n; ++j) {
        seek_seq[j] = -1;
    }

    printf("二分查找-----\n");
    bin_search(array, n, k, seek_seq);

    printf("查找顺序:");
    for (int j = 0; j < n; ++j) {
        if(seek_seq[j] < 0){
            break;
        }
        printf(" %d", array[seek_seq[j]]);
    }
}